package Servlets.yz;

import Bean.User;
import Util.GokJDBCUtil2;
import Util.SlatMD5Util;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

import static Util.SlatMD5Util.generateSaltPassword;

/*
* 用于用户注册功能
* */
@WebServlet(name="RegisServlet" , urlPatterns = "/RegisServlet")
public class RegisServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String method = req.getParameter("method");
        if("add".equals(method)){
            String username = req.getParameter("username");
            String nickname = req.getParameter("nickname");
            String phone = req.getParameter("phone");
            String address = req.getParameter("address");
            String useremail = req.getParameter("useremail");
            String password = SlatMD5Util.generateSaltPassword(req.getParameter("confirm_password"));
            LocalDateTime dateTime = LocalDateTime.now();
            String sql = "insert into user (username,userpassword,usernickname,userphone,useremail,useraddress,registertime) values(?,?,?,?,?,?,?)";
            GokJDBCUtil2.update(sql,username,password,nickname,phone,useremail,address,dateTime);
            resp.sendRedirect(req.getContextPath()+"/pages/registerSuccess.jsp");//重定向转向注册成功页面
        }
        else {//后端表单验证，查询数据库中的名字，如果有重复名字，数据库找到相应的对象，然后返回false,反之true
            String username = req.getParameter("username");
            if(username == null || username.trim().isEmpty()){
                writer.print("{\"flag\":false}");
            }
            else {
                String sql = "select * from user where username=?";
                User user = GokJDBCUtil2.queryForObject(sql, User.class, username);
                if(user ==null){
                    writer.print("{\"flag\":true}");
                }
                else {
                    writer.print("{\"flag\":false}");
                }
            }

            }/*最外层的if--else结尾*/

        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
